<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\Article as Info;

class Article extends Controller
{
    public function list(Request $request)
    {
        $typeId = $this->typeToId($request->type);
        
        $searchType = $request->input('search.type');
        $searchvalue = $request->input('search.value');

        $data = Info::whereType($typeId)->when($searchType, function($query) use ($searchType, $searchvalue)
        {
            switch ($searchType) {
                case 'views':
                    $query->orderBy($searchType, 'desc');
                    break;

                case 'is_show':
                case 'is_show_index':
                    $query = $query->where($searchType, $searchvalue);
                    break;
                
                default:
                    $query->where($searchType, 'like', '%'.$searchvalue.'%');
                    break;
            }

            return $query;

        }, function ($query) {
            return $query->latest();
        })->paginate(20)->toArray();

        return [
            'pages' => $this->getPages($data),
            'datas' => $data['data'],
        ];
    }

    public function info(Request $request)
    {
        $id = $request->id;
        return Info::select('id', 'title', 'cover', 'body', 'other_infos', 'fake_views')->find($id);
    }

    public function new(Request $request) {
        $id = $request->id;

        if ($id) {
            $data = Info::find($id);
        } else {
            $data = new Info;
        }

        $data->title = $request->title;
        $data->type = $this->typeToId($request->type);
        $data->cover = $request->cover;
        $data->fake_views = (int) $request->fake_views;
        $data->body = $request->body;

        $data->save();

        return $this->code(200);
    }

    public function put(Request $request)
    {
        $id = $request->id;
        $info = Info::find($id);

        $name = $request->name;
        $value = $request->value;

        if ($name == 'delete') {
            $info->delete();
        } else {
            $info->$name = $value;
            $info->save();
        }

        return $this->code(200);
    }
}
